using AutoMapper;
using B.S.Medical.Api.Read.Application.Command.Doctor;
using B.S.Medical.Api.Read.DTOS;
using B.S.Medical.Domain.Doctor;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.Medical.Api.Read.Application.Handler.Doctor
{
    /// <summary>
    /// 获取标签处理器
    /// </summary>
    public class GetLabelHandler : IRequestHandler<GetLabelCommand, ApiResult<List<LabelDTO>>>
    {
        private readonly IBaseRepository<LabelModel> labelRepo;
        private readonly ILogger<GetLabelHandler> logger;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="labelRepo">标签仓储</param>
        /// <param name="logger">日志记录器</param>
        public GetLabelHandler(IBaseRepository<LabelModel> labelRepo, ILogger<GetLabelHandler> logger,IMapper mapper)
        {
            this.labelRepo = labelRepo;
            this.logger = logger;
            this.mapper = mapper;
        }

        /// <summary>
        /// 处理获取标签请求
        /// </summary>
        /// <param name="request">获取标签命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>标签DTO</returns>
        public Task<ApiResult<List<LabelDTO>>> Handle(GetLabelCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<List<LabelDTO>> res=new ApiResult<List<LabelDTO>>();
                var label = labelRepo.GetAll().Where(a => !a.IsDeleted);
                res.Code = ApiEnum.Success;
                res.Msg = "处理获取标签请求成功";
                res.Data=mapper.Map<List<LabelDTO>>(label.ToList());
                return Task.FromResult(res);

            }
            catch (System.Exception ex)
            {
                logger.LogError(ex, "获取标签时发生错误");
                throw;
            }
        }
    }
}